﻿@using ST.Torch.WebApi.Web.Core;
@inherits UtilRazorPage<object>
@{
    Layout = "~/Views/Shared/__ComponentLayout.cshtml";
    string randomId = Guid.NewGuid().ToString();
}
    <div style="padding: 5px;">
        <div class="layui-card">
            <div class="layui-card-body">
            <table class="layui-hide" id="tableEle_@randomId" lay-filter="tableEle_@randomId"></table>
            </div>
        </div>
    </div>

@section footer
{
    <script type="text/html" id="toolbarDemo_@randomId">
         <div style="display:flex">
             <div style="flex:1">
                  <div class="layui-btn-container">
                      <button class="layui-btn layui-btn-sm" lay-event="AddData"><i class="layui-icon layui-icon-add-circle"></i>@L("新增")</button>
                      <button type="button" class="layui-btn layui-btn-sm" id="ImportExcelDataEle_@randomId" lay-event="ImportExcelData"><i class="layui-icon layui-icon-upload-drag"></i>@L("导入excel")</button>
                      <button class="layui-btn layui-btn-sm" lay-event="ExportExcelData"> <i class="layui-icon layui-icon-download-circle"></i>@L("导出excel")</button>
                      <button class="layui-btn layui-btn-sm" lay-event="ExportExcelModel"> <i class="layui-icon layui-icon-download-circle"></i>@L("下载导入excel模板")</button>
                      <button class="layui-btn layui-btn-sm" lay-event="DelData"> <i class="layui-icon layui-icon-delete"></i>@L("删除")</button>
                      
                     
                </div>
             </div>
            <div style="width:200px;display:flex">
                 <input type="text"  id="Querykey_@randomId" placeholder="" style="display: inline-block;height: 30px; line-height: 30px;margin-right:5px" class="layui-input">
                 <button class="layui-btn layui-btn-sm" lay-event="QueryData">@L("查询")</button>
            </div>

        </div>
    </script>
    <script type="text/html" id="barDemo_@randomId">
        <div class="layui-clear-space">
          <button class="layui-btn layui-btn-xs" lay-event="edit">@L("编辑")</button>

          
          <a class="layui-btn layui-btn-xs" lay-event="more">
                @L("更多")
            <i class="layui-icon layui-icon-down"></i>
          </a>
        </div>
    </script>
  
    <script>

        layui.use(['table', 'toast', 'dropdown', 'jquery', 'upload', 'element'], function () {
            var  table = layui.table;
            var dropdown = layui.dropdown;
            var form = layui.form;
            var toast = layui.toast;
            var upload = layui.upload;
            var $ = layui.jquery;
            var element = layui.element;
           
            // 创建渲染实例
            table.render({
                elem: '#tableEle_@randomId',
                url: '/api/UtilExcel/GetDataPagedList', // 此处为静态模拟数据，实际使用时需换成真实接口
                method: 'post',//如果无需自定义HTTP类型，可不加该参数
                toolbar: '#toolbarDemo_@randomId',
                defaultToolbar: ['filter', 'exports', 'print', {
                    title: '提示',
                    layEvent: 'LAYTABLE_TIPS',
                    icon: 'layui-icon-tips'
                }],
                height: 'full-135', // 最大高度减去其他容器已占有的高度差
                limit: 20,//注意：请务必确保 limit 参数（默认：10）是与你服务端限定的数据条数一致
                css: [ // 重设当前表格样式
                    '.layui-table-tool-temp{padding-right: 145px;}'
                ].join(''),
                cellMinWidth: 80,
                //totalRow: true, // 开启合计行
                page: true,
                cols: [[
                    { type: 'checkbox', fixed: 'left' },
                    { field: 'Column1', title: '@L("列1")' },
                    { field: 'Column2', title: '@L("列2")' },
                    { field: 'Column3', title: '@L("列3")' },
                    { field: 'Column4', title: '@L("列4")' },
                    { field: 'Column5', title: '@L("列5")' },
                    { fixed: 'right', title: '@L("操作")', width: 150, minWidth: 150, toolbar: '#barDemo_@randomId' }
                ]],
                parseData: function (res) {
                    console.log(res)
                    return {
                        "count": res.Data.TotalCount,
                        'statusCode': res.StatusCode,
                        'data': res.Data.Items
                    };
                },
                response: {
                    statusName: 'statusCode',
                    statusCode: 200
                },
                done: function () {
                    var id = this.id;
                    permissionUI();
                },
                error: function (res, msg) {
                    console.log(res, msg)
                }
            });

            var progressTime = null;
            var progressKey = 'progressKey_@randomId)';
            console.log("---.jpg|png|gif----!")
            //指定允许上传的文件类型
            var uploadInst = upload.render({
                elem: '#ImportExcelDataEle_@randomId'
                
                , url: '/api/UtilExcel/ImportExcelfiles/TemporaryFiles'
                , accept: 'file' //普通文件
                 , acceptMime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel'//规定打开文件选择框时，筛选出的文件类型，值为用逗号隔开的 MIME 类型列表
                , exts: 'xlsx|xls'//允许上传的文件后缀
                , data: {
                    AutofileName:progressKey,
                }
                ,progress: function (e, percent) {
                    console.log(JSON.stringify(e));
                    var htmlStr=("进度：" + e + '%');
                    $("#progressMsg").html("@L("上传文件中"):" + htmlStr)
                    //element.progress('progressBar', e + '%');
                }
                , before: function (res) {
                    var progressHtml = `<div class="layui-progress layui-progress-big" lay-filter="div-filter-progress" lay-showpercent="true">
                                            <div class="layui-progress-bar" lay-percent="0%">
                                            </div>
                                        </div>`;
                    var titleName = '@L("导入数据")'
                    var titleMsg = '@L("导入中")'
                    layer.open({
                        type: 1
                        , offset: 'auto' //具体配置参考：/v2/docs/modules/layer.html#offset
                        , id: 'layerDemoAuto' //防止重复弹出
                        , title: titleName
                        , content: '<div style="padding: 20px 5px;">' + progressHtml + '  <div class="layui-font-red" id="progressMsg" style="text-align: center;" >' + titleMsg + '</div></div>'
                        , area: ['30%', '200px']
                        , btn: '关闭'
                        , btnAlign: 'c' //按钮居中
                        , shade: 0 //不显示遮罩
                        , yes: function () {//取消
                            clearInterval(progressTime)
                            GetProgressPercent(progressKey, 'div-filter-progress', true)
                            progressKey = progressKey + Date.now()
                            uploadInst.reload({
                                data: {
                                    AutofileName: progressKey,
                                }
                            })

                            layer.closeAll();
                        }, cancel: function (index, layero) {
                            console.log("=====cancel========")
                            layer.close(index);
                            clearInterval(progressTime)
                            GetProgressPercent(progressKey, 'div-filter-progress', true)
                        }
                    });
                    // 渲染进度条组件
                    element.render('progress', 'div-filter-progress');
                   // GetProgressPercent(progressKey, 'div-filter-progress')
                    progressTime = setInterval(function () { GetProgressPercent(progressKey, 'div-filter-progress') }, 300)
                    
              
                }
                , done: function (res) {
                    clearInterval(progressTime)
                    console.log(res)
                    GetProgressPercent(progressKey, 'div-filter-progress')
                    progressKey = progressKey + Date.now()
                    uploadInst.reload({
                        data: {
                            AutofileName: progressKey,
                        }
                    })
                    if (res.code == 200) {

                        $("#progressMsg").addClass("layui-font-green")
                        $("#progressMsg").html("@L("导入成功")")
                        
                        reloadTableData();
                    } else {
                        $("#progressMsg").html(res.msg)
                    }
                }
            });
            // 工具栏事件
            table.on('toolbar(tableEle_@randomId)', function (obj) {
                var id = obj.config.id;
                var checkStatus = table.checkStatus(id);
                var othis = lay(this);
                switch (obj.event) {
                    case 'QueryData':
                        var key = $("#Querykey_@randomId").val();
                        table.reloadData('tableEle_@randomId', {
                            where: {
                                key: key,
                            },

                            page: { curr: 1, limit: 20 } // 重新指向分页
                        });
                        break;
                    case 'AddData':
                        var buttonEle = button.load({ elem: this });
                        var msgTitle = '@L("新增数据")'
                        console.log('新增数据');
                        GetViewHtml('/Utils/Excel/RenderViewToString', 'AddOrEdit', [], function (html) {
                            layer.open({
                                title: msgTitle,
                                type: 1,
                                area: ['40%', '60%'],
                                content: html,
                                success: function (layero, index, that) {
                                    G_LayuiOpenTypeIndex = index;
                                },
                                end: function (index, layero) {
                                    // 这里写关闭窗口后需要执行的代码
                                    console.log('窗口被关闭了End');
                                    reloadTableData();
                                },
                            });
                            buttonEle.stop();
                        })
                        break;
                    case 'DelData':
                        var data = checkStatus.data;
                        //obj.del(); // 删除对应行（tr）的DOM结构
                        console.log(data)
                        if (data.length >= 1) {
                            var msgTitle = '@L("确定删除选中的数据吗?")'
                            layer.confirm(msgTitle, function (index) {
                                var Ids = [];
                                for (var i in data) {
                                    Ids.push(data[i].Id)
                                }
                                DelBatchData(Ids)
                                layer.close(index);
                            });

                        } else {
                            var msgTitle = '@L("请选择要删除的数据")'
                            layer.alert(msgTitle);
                        }
                        break;
                    case 'ImportExcelData':
                       
                        break;
                    case 'ExportExcelData':
                        Exporte();
                        break;
                    case 'ExportExcelModel':
                        ExporteModel();
                        break;
                        
                    case 'LAYTABLE_TIPS':
                        layer.alert('自定义工具栏图标按钮');
                        break;
                };
            });
            // 表头自定义元素工具事件 --- 2.8.8+
            table.on('colTool(tableEle_@randomId)', function (obj) {
                var event = obj.event;
                console.log(obj);
                if (event === 'email-tips') {
                    layer.alert(layui.util.escape(JSON.stringify(obj.col)), {
                        title: '当前列属性配置项'
                    });
                }
            });

            // 触发单元格工具事件
            table.on('tool(tableEle_@randomId)', function (obj) { // 双击 toolDouble
                var data = obj.data; // 获得当前行数据
                if (obj.event === 'edit') {
                    var buttonEle = button.load({ elem: this });
                    var msgTitle = '@L("编辑")【' + data.Column1 + '】';
                    GetViewHtml('/Utils/Excel/RenderViewToString', 'AddOrEdit', [data.Id], function (html) {
                        layer.open({
                            title: msgTitle,
                            type: 1,
                            area: ['40%', '60%'],
                            content: html,
                            success: function (layero, index, that) {
                                G_LayuiOpenTypeIndex = index;
                            },
                            end: function (index, layero) {
                                // 这里写关闭窗口后需要执行的代码
                                console.log('窗口被关闭了End');
                                reloadTableData();
                            },
                        });
                        buttonEle.stop();
                    })

                } else if (obj.event === 'more') {
                    var dataDrop=[];
                    dataDrop.push({
                            title: '@L("查看")',
                            id: 'detail'
                        })
                    if(IsPermission('GeneralDelDataPerm')){
                        dataDrop.push( {
                            title: '@L("删除")',
                            id: 'del'
                        })
                    }
                    // 更多 - 下拉菜单
                    dropdown.render({
                        elem: this, // 触发事件的 DOM 对象
                        show: true, // 外部事件触发即显示
                        data:dataDrop,
                    
                        click: function (Roledata) {
                            if (Roledata.id === 'detail') {
                                //layer.msg('查看操作，当前行 ID:' + data.id);
                                var msg = '@L("当前列数据")'
                                layer.alert(layui.util.escape(JSON.stringify(data)), {
                                    title: msg
                                });
                            } else if (Roledata.id === 'del') {
                                var msg = '@L("确认删除行")';
                                layer.confirm(msg + ' [' + data.Column1 + '] ?', function (index) {
                                    obj.del(); // 删除对应行（tr）的DOM结构
                                    DelData(data.Id);
                                    layer.close(index);
                                });
                            }
                        },
                        align: 'right', // 右对齐弹出
                        style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' // 设置额外样式
                    })
                }
            });

            // 触发表格复选框选择
            table.on('checkbox(tableEle_@randomId)', function (obj) {
                console.log(obj)
            });

            // 触发表格单选框选择
            table.on('radio(tableEle_@randomId)', function (obj) {
                console.log(obj)
            });

            // 行单击事件
            table.on('row(tableEle_@randomId)', function (obj) {
                //console.log(obj);
                //layer.closeAll('tips');
            });
            // 行双击事件
            table.on('rowDouble(tableEle_@randomId)', function (obj) {
                console.log(obj);
            });



            // 单元格编辑事件
            table.on('edit(tableEle_@randomId)', function (obj) {
                var field = obj.field; // 得到字段
                var value = obj.value; // 得到修改后的值
                var data = obj.data; // 得到所在行所有键值
            });


            function DelData(Id) {
                var formData = {
                    Id: Id
                };
                $.ajax({
                    type: 'POST',
                    url: '/api/UtilExcel/Delete',//发送请求
                    data: formData,
                    success: function (result) {
                        console.log(result)
                        if (result.Succeeded) {
                                toast.success({
                                    message: '@L("删除成功")',
                                });
                                reloadTableData()
                        } else {
                            toast.error({
                                message: '@L("删除失败")',
                            });
                        }
                    }
                });
            }
            function DelBatchData(Ids) {
                var formData = {
                    Ids: Ids
                };
                $.ajax({
                    type: 'POST',
                    url: '/api/UtilExcel/DeleteBatch',//发送请求
                    data: formData,
                    success: function (result) {
                        console.log(result)
                        if (result.Succeeded) {
                            toast.success({
                                message: '@L("删除成功")',
                            });
                            reloadTableData()
                        } else {
                            toast.error({
                                message: '@L("删除失败")',
                            });
                        }
                    }
                });
            }

            function GetProgressPercent(key,ele,IsCancel=false) {
                console.log("-GetProgressPercent-")
                var formData = {
                    key: key,
                    IsCancel: IsCancel
                };
                $.ajax({
                    type: 'POST',
                    url: '/api/UtilExcel/GetProgressPercent',//发送请求
                    data: formData,
                    success: function (result) {
                        console.log(result)
                        if (result.Data != "100") {
                            var titleMsg = '@L("导入中")';
                            $("#progressMsg").html(titleMsg)
                        }

                        element.progress(ele, parseInt(result.Data)+"%")
                      
                    }
                });
            }
            function Exporte(){
                var key = $("#Querykey_@randomId").val();

                window.location = "/api/UtilExcel/ExPortExcel?key=" + key;
            }
            function ExporteModel() {
                window.location = "/api/UtilExcel/ExPortExcel?key=A11";
            }
            

            function reloadTableData() {
                var key = $("#Querykey_@randomId").val();
                table.reloadData('tableEle_@randomId', {
                    where: {
                        key: key,
                    },
                });
            }


        });

    </script>

}